from tool import send, read_cfg, write_cfg, log
import time


def get_data(cfg):
    try:
        st = None

        if not cfg:
            cfg = {}

        if "real" in cfg:
            st = cfg["real"]

        if st:
            body = send("http://127.0.0.1:9983/timedb/get", {
                "n": "real",
                "obj": "*",
                "opt": {
                    "and": [{"gt": "time", "v": st}]
                    }
                })
        else:
            body = send("http://127.0.0.1:9983/timedb/get", {
                "n": "real",
                "obj": "*",
                })

        if "data" not in body:
            return None

        cfg["real"] = body['end']

        body = body["data"]

        return body
    except Exception as e:
        log("do up error: %s" % e)

    return None


def do_up(cfg):
    line = cfg["line"]
    wsn = cfg["wsn"]
    ip = cfg["ip"]

    while True:
        try:
            cfg = read_cfg()

            body = get_data(cfg)

            if not body:
                continue

            for d in body:
                psn = d["psn"]
                tsn = d["tsn"]
                width = d["width"]
                dia = d["dia"]

                send("http://%s/timedb/chunk" % ip, {
                    "tab": "outwidth",
                    "line": line,
                    "data": [{
                        "psn": psn,
                        "wsn": wsn,
                        "k": {
                            "tsn": tsn,
                            },
                        "v": {
                            "val": width,
                            }
                        }]
                    })

                send("http://%s/timedb/chunk" % ip, {
                    "tab": "outdia",
                    "line": line,
                    "data": [{
                        "psn": psn,
                        "wsn": wsn,
                        "k": {
                            "tsn": tsn,
                            },
                        "v": {
                            "val": dia,
                            }
                        }]
                    })

            write_cfg(cfg)
        except Exception as e:
            log("do up error: %s" % e)

        time.sleep(10)
